﻿#define GUILITE_ON  //Do not define this macro once more!!!
#include "GuiLite.h"
#include <stdlib.h>

#define UI_WIDTH 128
#define UI_HEIGHT 64

static c_surface* s_surface;
static c_display* s_display;

extern const BITMAP_INFO test_icon;
extern const BITMAP_INFO bear;

class c_star {
public:
	c_star(){
        m_role = nullptr;
		initialize();
	}
	void initialize() {
		m_x = m_start_x = rand() % UI_WIDTH;
		m_y = m_start_y = rand() % UI_HEIGHT;
		m_x_factor = UI_WIDTH;
		m_y_factor = UI_HEIGHT;
		m_move_factor = 3;
	}
	void set_role(const BITMAP_INFO *role)
	{
		if(role)
		{
			m_role = role;
		}
	}
	void role_move(int pos_x, int pos_y){
        if ((m_x != pos_x) || (m_y != pos_y))
		{
			s_surface->fill_rect(m_x, m_y, m_x + m_role->width - 1, m_y + m_role->height - 1,
				0, Z_ORDER_LEVEL_0);
		}
    	c_image::draw_image(s_surface, Z_ORDER_LEVEL_0, m_role, pos_x, pos_y);
		m_start_x = pos_x;
		m_start_y = pos_y;
	}
	void move(int direction) {
		switch (direction)
		{
			default:
			case 0: /* TODO stop */
				return;
				/* UP */
			case 1:
				m_y = m_start_y;
				m_start_y -= m_move_factor;
				if (m_start_y < 0)
					m_start_y = 0;
				break;
				/* DOWN */
			case 2:
				m_y = m_start_y;
				m_start_y += m_move_factor;
				if (m_start_y > m_y_factor)
					m_start_y = m_y_factor;
				break;
				/* LEFT */
			case 3:
				m_x = m_start_x;
				m_start_x -= m_move_factor;
				if (m_start_x < 0)
					m_start_x = 0;
				break;
				/* RIGHT */
			case 4:
				m_x = m_start_x;
				m_start_x += m_move_factor;
				if (m_start_x > m_x_factor)
					m_start_x = m_x_factor;
				break;
		}
        role_move(m_start_x, m_start_y);
	}
	int m_start_x, m_start_y;
	float m_x, m_y, m_x_factor, m_y_factor, m_move_factor;
    const BITMAP_INFO *m_role;
};

//////////////////////// start UI ////////////////////////

c_star stars[30];
void create_ui(void* phy_fb, int screen_width, int screen_height, int color_bytes, struct DISPLAY_DRIVER* driver) {
	static c_surface surface(UI_WIDTH, UI_HEIGHT, color_bytes, Z_ORDER_LEVEL_0);
	static c_display display(phy_fb, screen_width, screen_height, &surface, driver);
	s_surface = &surface;
	s_display = &display;

	s_surface->fill_rect(0, 0, UI_WIDTH - 1, UI_HEIGHT - 1, 0, Z_ORDER_LEVEL_0);

//	c_image::draw_image(s_surface, Z_ORDER_LEVEL_0, &bear, 30, 20);
    stars[0].set_role(&bear);
	while(1) {
		for (int i = 0; i < sizeof(stars)/sizeof(c_star); i++) {
			stars[0].move(i % 4 + 1);
    		thread_sleep(1000);
		}
		thread_sleep(50);
	}
}

//////////////////////// interface for all platform ////////////////////////
extern "C" void startHelloStar(void* phy_fb, int width, int height, int color_bytes, struct DISPLAY_DRIVER* driver) {
	create_ui(phy_fb, width, height, color_bytes, driver);
}

void* getUiOfHelloStar(int* width, int* height, bool force_update)
{
	if (s_display)
	{
		return s_display->get_updated_fb(width, height, force_update);
	}
	return NULL;
}
